/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2024-2024. All rights reserved.
 *
 */
import path from 'path';
import { hvigor } from '@ohos/hvigor';
import { FileUtil } from './file-util.js';
import { resModelLoader } from './loader/file/res-model-loader.js';
import { CommonConst } from '../const/common-const.js';

/**
 * 判断是否是源码目录迁移后的模板
 *
 * @param {string} srcOhosTestPath ohosTest默认源码目录
 * @return {boolean} true/false
 */
export function isTemplatesAfterSourceCodeMigration(srcOhosTestPath: string): boolean {
  const moduleOptObj = resModelLoader.getModuleJson(path.resolve(srcOhosTestPath, CommonConst.MODULE_JSON5));
  const abilityObj = moduleOptObj?.module?.abilities;
  if (abilityObj && abilityObj.length) {
    const srcEntry = abilityObj[0].srcEntry;

    // 若配置了ability和srcEntry，则视为简化目录后的模板，此时返回false
    return !srcEntry;
  }

  // 上述ability不存在，且testRunner不存在时，返回true，判定为简化目录后的工程模板
  return !(
    FileUtil.matchingFile(path.resolve(srcOhosTestPath, 'ets/testrunner/OpenHarmonyTestRunner.ets'), true) ||
    FileUtil.matchingFile(path.resolve(srcOhosTestPath, 'ets/testrunner/OpenHarmonyTestRunner.ts'), true)
  );
}

export function getOhosTestIntermediatesPath(modulePath: string): string {
  return path.resolve(modulePath, getOhosTestIntermediatesRelativePath());
}

export function getOhosTestIntermediatesRelativePath() {
  const productName = hvigor.getParameter().getExtParam('product') ?? 'default';
  return `build/${productName}/intermediates`;
}

export function getOhosTestIntermediatesEtsPath(modulePath: string): string {
  return path.resolve(getOhosTestIntermediatesPath(modulePath), 'src/ohosTest/ets');
}

export function getOhosTestIntermediatesSrcResource(modulePath: string) {
  return path.resolve(getOhosTestIntermediatesPath(modulePath), 'src/ohosTest/resources');
}

export function getOhosTestAbilityConfig() {
  return {
    description: '$string:module_test_desc',
    mainElement: 'TestAbility',
    pages: '$profile:test_pages',
    abilities: [
      {
        name: 'TestAbility',
        srcEntry: './ets/testability/TestAbility.ets',
        description: '$string:TestAbility_desc',
        label: '$string:TestAbility_label',
        exported: true,
      },
    ],
  };
}
